package com.cf.web.servlet;
import com.alibaba.fastjson.JSONObject;
import com.cf.dao.UserDao;
import com.cf.dao.entity.User;
import com.cf.dao.entity.session;
import com.cf.dao.impl.UserDaoImpl;
import com.cf.web.util.MailUtil;
import com.cf.web.util.RequestUtil;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Random;
@WebServlet(name = "UserServlet", value = "/user/*")
public class UserServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();
    private session sessions = new session();
    public int id = 0;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getPathInfo();
        if ("/getUserbyid".equals(path)) {
            getUserById(request, response);
        }else if("/getUsercode".equals(path)){
            try {
                getUsercode(request,response);
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
        else if ("/getSessionUser".equals(path)){
                session(request, response);
            }
    else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "路径不存在");
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getPathInfo();
        if ("/login".equals(path)) {
            login(request, response);
        } else if ("/register".equals(path)) {
            register(request, response);
        } else if ("/updateProfile".equals(path)) {
            updateProfile(request, response);
        } else if ("/logout".equals(path)) {
            logout(request, response);
        }else  if ("/getUserbyid".equals(path)) {
                getUserById(request, response);
        }else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "路径不存在");
        }
    }
    //用户登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject param = RequestUtil.getParam(request);
        System.out.println(param);
        sessions.setUserid(0);
        response.setContentType("application/json; charset=UTF-8");
        JSONObject result = new JSONObject();
        if (param == null) {
            result.put("success", false);
            result.put("message", "请求参数缺失或无效");
            response.getWriter().write(result.toJSONString());
            return;
        }
        String account = param.getString("account");
        String password = param.getString("password");
        if (account != null && password != null && !account.trim().isEmpty() && !password.trim().isEmpty()) {
            try {
                User user = userDao.selectUserByAccountAndPwd(account.trim(), password.trim());
                if (user != null) {
                    if (user != null) {
                        HttpSession session = request.getSession(true);  // true 表示如果 session 不存在就创建新的
                        session.setAttribute("id", user.getId()); // 存储用户 ID
                        session.setAttribute("user", user); // 存储用户姓名
//                        session.setAttribute("account", user.getAccount()); // 存储用户账号
                        sessions.setUserid(user.getId());
                        System.out.println(user.getId());
                        System.out.println("+"+sessions.getUserid());
                        result.put("success", true);
                        result.put("message", "登录成功");
                        response.getWriter().write(result.toJSONString());
                    }
                } else {
                    result.put("success", false);
                    result.put("message", "无效的帐户或密码");
                    response.getWriter().write(result.toJSONString());
                }
            } catch (SQLException e) {
                result.put("success", false);
                result.put("message", "数据库错误，请稍后再试");
                response.getWriter().write(result.toJSONString());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "发生意外错误，请再试一次");
                response.getWriter().write(result.toJSONString());
            }
        } else {
            result.put("success", false);
            result.put("message", "帐户和密码不能为空");
            response.getWriter().write(result.toJSONString());
        }
    }
    //用户注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK); // 设置响应状态码为 200 OK
        JSONObject result = new JSONObject();
        try {
            // 获取请求参数
            JSONObject param = RequestUtil.getParam(request);
            if (param == null) {
                throw new IllegalArgumentException("请求参数不能为空");
            }
            String account = param.getString("account");
            String password = param.getString("password");
            String emailcode = param.getString("vcode");
            String email = param.getString("email");
            // 校验输入参数
            if (account == null || account.trim().isEmpty() ||
                    password == null || password.trim().isEmpty() ||
                    email == null || email.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "帐户、密码和邮箱不能为空");
                response.getWriter().write(result.toJSONString());
                return;
            }
            if (emailcode == null || emailcode.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "验证码不能为空");
                response.getWriter().write(result.toJSONString());
                return;
            }
            // 检查账户是否已存在
            User existingUser = userDao.selectUserByAccount(account.trim());
            if (existingUser != null) {
                result.put("success", false);
                result.put("message", "账户已存在");
                response.getWriter().write(result.toJSONString());
                return;
            }
            // 检查邮箱是否已存在
            boolean existingEmailUser = userDao.selectUserByEmail(email.trim());
            if (existingEmailUser) {
                result.put("success", false);
                result.put("message", "邮箱已存在");
                response.getWriter().write(result.toJSONString());
                return;
            }
            // 验证验证码是否有效
            boolean isValid = isVerificationCodeValid(request, emailcode);
            if (!isValid) {
                result.put("success", false);
                result.put("message", "验证码无效或已过期");
                response.getWriter().write(result.toJSONString());
                return;
            }
            // 验证码验证通过
            if (emailcode.equals(sessions.getCode())) {
                User newUser = new User();
                newUser.setAccount(account.trim());
                newUser.setPassword(password.trim());
                newUser.setEmail(email.trim());
                userDao.insertUser(newUser);
                result.put("success", true);
                result.put("message", "注册成功");
                response.getWriter().write(result.toJSONString());
            } else {
                result.put("success", false);
                result.put("message", "验证码错误");
                response.getWriter().write(result.toJSONString());
            }
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            response.getWriter().write(result.toJSONString());
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "数据库错误：" + e.getMessage());
            response.getWriter().write(result.toJSONString());
            e.printStackTrace();
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发生意外错误：" + e.getMessage());
            response.getWriter().write(result.toJSONString());
            e.printStackTrace();
        }
    }
    //用户信息更新
    private void updateProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject param = RequestUtil.getParam(request);
        response.setContentType("application/json; charset=UTF-8");
        JSONObject result = new JSONObject();
        // 确认 param 是否为 null
        if (param == null) {
            response.sendRedirect("editProfile.jsp?error=Invalid parameters");
            return;
        }
        // 获取当前登录用户
        User currentUser = (User) request.getSession().getAttribute("user");
        if (currentUser == null) {
            response.sendRedirect("/vscf/login.html");
            return;
        }
        // 获取提交的个人信息
        String name = param.getString("name");
        String sexy = param.getString("sexy");
        String password = param.getString("password");
        String ageStr = param.getString("age");
        // 验证年龄是否为正整数
        int age = 0;
        try {
            age = Integer.parseInt(ageStr);
        } catch (NumberFormatException e) {
            age = -1;  // 如果无法解析为整数，设置默认值
        }
        // 验证参数有效性
        if (name == null || sexy == null || age <= 0) {
            response.sendRedirect("editProfile.jsp?error=All fields are required and age must be a positive number.");
            return;
        }
        // 验证用户 ID 是否有效
        if (currentUser.getId() == 0) {
            response.sendRedirect("editProfile.jsp?error=Invalid user ID.");
            return;
        }
        // 如果密码为空，表示用户没有修改密码，不需要更新密码
        boolean isPasswordChanged = (password != null && !password.isEmpty());
        // 调用 DAO 更新用户信息
        try {
            boolean success = false;
            // 如果密码修改了，更新密码
            if (isPasswordChanged) {
                success = userDao.updateUserProfile(currentUser.getId(), name, age, sexy, password);
            } else {
                success = userDao.updateUserProfile(currentUser.getId(), name, age, sexy);
            }
            // 更新 session 中的用户信息
            if (success) {
                currentUser.setName(name);
                currentUser.setSexy(sexy);
                currentUser.setAge(age);
                // 如果修改了密码，也更新 session 中的密码
                if (isPasswordChanged) {
                    currentUser.setPassword(password);
                }
                // 更新用户信息到 session
                request.getSession().setAttribute("user", currentUser);

                // 返回成功的响应
                result.put("success", true);
                result.put("message", "修改成功");
            } else {
                result.put("success", false);
                result.put("message", "发生意外错误，请再试一次");
            }
            response.getWriter().write(result.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "发生意外错误，请再试一次");
            response.getWriter().write(result.toJSONString());
        }
    }

    // 登出操作
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:/vscf/login.html";
    }
    // 根据用户ID获取用户信息
    public void getUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json; charset=UTF-8");
        JSONObject result = new JSONObject();
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 获取参数
            String idParam = request.getParameter("id");
            if (idParam == null || !idParam.matches("\\d+")) {
                result.put("success", false);
                result.put("message", "参数缺失或无效");
                out.write(result.toJSONString());
                return;
            }
            int id = Integer.parseInt(idParam);
            // 查询用户信息
            User user = userDao.selectUserById(id);
            if (user == null) {
                result.put("success", false);
                result.put("message", "未找到指定用户");
                out.write(result.toJSONString());
                return;
            }
            // 构造成功响应
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", JSONObject.toJSON(user)); // 使用 Fastjson 序列化对象
            out.write(result.toJSONString());
        } catch (SQLException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "数据库查询出错");
            if (out != null) {
                out.write(result.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器内部错误");
            if (out != null) {
                out.write(result.toJSONString());
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    //获取注册验证码
    public void getUsercode(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        JSONObject result = new JSONObject();
        String code = "";
        String emailaddress = request.getParameter("email");
        if (emailaddress == null || emailaddress.isEmpty()) {
            result.put("success", false);
            result.put("message", "请输入邮箱地址");
            response.getWriter().write(result.toJSONString());
        }
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code = code + r;
        }
        MailUtil.send_mail(emailaddress, "本次服务的激活码为：" + code);
        System.out.println("邮件发送成功! " + code);
        long expirationTime = System.currentTimeMillis() + 5 * 60 * 1000;  // 5分钟有效期（单位：毫秒）
        sessions.setCode(code);
        sessions.setTime(expirationTime);
        result.put("success", true);
        result.put("message", "验证码已发送");
        response.getWriter().write(result.toJSONString());
    }
    //验证码时效性
    public boolean isVerificationCodeValid(HttpServletRequest request, String enteredCode) {
        String code = sessions.getCode();
        Long time = sessions.getTime();
        if (code == null || time == null || System.currentTimeMillis() > time) {
            return false;  // 验证码已过期
        }
        return code.equals(enteredCode);
    }

    // 获取当前登录用户信息
    private void session(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取 Session
        HttpSession httpSession = request.getSession(false);  // false: 如果没有 session，不创建新 session
        JSONObject result = new JSONObject();


            int userId = (Integer) httpSession.getAttribute("id");
//            int id = (int) request.getSession().getAttribute("id");  // 获取 session 中的 "id"
            int ids = sessions.getUserid();
            System.out.println("当前登录用户 ID: " + ids);
            if (userId != 0) {
                User user = null;
                try {
                    user = userDao.selectUserById(ids);
                    if (user != null) {
                        result.put("success", true);
                        result.put("user", new JSONObject()
                                .fluentPut("id", user.getId())
                                .fluentPut("name", user.getName())
                                .fluentPut("email", user.getEmail())
                                .fluentPut("avatar", user.getAvatar())
                                .fluentPut("sexy", user.getSexy())
                                .fluentPut("age", user.getAge())
                                .fluentPut("phone", user.getPhone())
                                .fluentPut("state", user.getState())
                                .fluentPut("account", user.getAccount())
                                .fluentPut("commentall", user.getCommentall())
                        );
                    } else {
                        result.put("success", false);
                        result.put("message", "用户信息不存在");
                    }
                } catch (SQLException e) {
                    result.put("success", false);
                    result.put("message", "数据库错误");
                }
            } else {
                result.put("success", false);
                result.put("message", "未登录");
            }


        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(result.toJSONString());
    }

    }


